package com.mall.user.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IUserLoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.CheckAuthRequest;
import com.mall.user.dto.CheckAuthResponse;
import com.mall.user.dto.CheckLoginRequest;
import com.mall.user.dto.CheckLoginResponse;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import tk.mybatis.mapper.entity.Example;


import java.util.List;

@Service
@Slf4j
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    MemberMapper memberMapper;

    @Override
    public CheckLoginResponse checkLogin(CheckLoginRequest request) {
        String username = request.getUsername();
        CheckLoginResponse response = new CheckLoginResponse();
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        try {
            Member member = memberMapper.selectByExample(example).get(0);
            if (member == null) {
                response.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                response.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            } else {
                response.setFile(member.getFile());
                response.setUid(member.getId());
                response.setUsername(username);
                response.setCode(SysRetCodeConstants.SUCCESS.getCode());
                response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            }
        } catch (Exception e) {
            log.error("MemberServiceImpl.checkLogin Occur exception : " + e);
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }
        return response;

    }

    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {
        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();
        try{
            JwtTokenUtils build = JwtTokenUtils.builder().token(checkAuthRequest.getToken()).build();
            String userInfo = build.freeJwt();
            checkAuthResponse.setUserInfo(userInfo);
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (ValidateException e) {
            checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
        }
        return checkAuthResponse;
    }
}
